package com.qk.management.aop;

import com.qk.common.Result;
import com.qk.entity.OperateLog;
import com.qk.management.mapper.OperateLogMapper;
import com.qk.management.util.CurrentUserContextHolders;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Arrays;
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.qk.management.anno.LogOperation)")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint){
        Object result = null;
        try {
            long startTime = System.currentTimeMillis();

            // 记录请求参数
            Object[] args = joinPoint.getArgs();
            String methodParams = Arrays.toString( args);

            // 执行目标方法
            result = joinPoint.proceed();

            // 计算耗时
            long costTime = System.currentTimeMillis() - startTime;

            // 保存日志
            OperateLog logs = new OperateLog();
            logs.setOperateUserId(CurrentUserContextHolders.getCurrentUserId()); //操作用户
            logs.setOperateTime(LocalDateTime.now()); // 操作时间
            logs.setClassName(joinPoint.getTarget().getClass().getName()); // 类名
            logs.setMethodName(joinPoint.getSignature().getName()); // 方法名
            logs.setMethodParams(methodParams); // 参数
            logs.setReturnValue(result.toString()); // 返回值
            logs.setCostTime(costTime); // 耗时

            try {
                operateLogMapper.insert(logs);
            } catch (Exception e) {
                log.info("日志异常:{}",e);
            }
        } catch (Throwable e) {
            return Result.error("操作失败，请稍后重试");
        }
        return result;
    }
    
}